package cn.netswap.jeegorilla.framework.security.filter;

import cn.netswap.jeegorilla.framework.security.bean.ImageValidCode;
import cn.netswap.jeegorilla.framework.security.bean.SmsValidCode;
import cn.netswap.jeegorilla.framework.security.bean.ValidCode;
import cn.netswap.jeegorilla.framework.security.consts.SecurityConstants;
import cn.netswap.jeegorilla.framework.security.exception.ValidateCodeException;
import cn.netswap.jeegorilla.framework.security.handler.GorillaAuthenticationFailureHandler;
import cn.netswap.jeegorilla.framework.security.web.GorillaSecurityController;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.social.connect.web.HttpSessionSessionStrategy;
import org.springframework.social.connect.web.SessionStrategy;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author lgw
 * @version 1.0
 * @date 2020/3/19 16:03
 */
public class ImageValidCodeFilter extends OncePerRequestFilter {

    private GorillaAuthenticationFailureHandler gorillaAuthenticationFailureHandler;

    @Autowired
    private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy();

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        if (SecurityConstants.DEFAULT_LOGIN_URL.equals(request.getRequestURI()) && SecurityConstants.DEFAULT_POST_METHOD.equals(request.getMethod())) {
           try {
               validate(new ServletWebRequest(request),SecurityConstants.DEFAULT_LOGIN_URL);
               filterChain.doFilter(request, response);
           } catch (ValidateCodeException e) {
               gorillaAuthenticationFailureHandler.onAuthenticationFailure(request, response, e);
               return;
           }
        }else if((SecurityConstants.DEFAULT_SMS_LOG_URL.equals(request.getRequestURI()) && SecurityConstants.DEFAULT_POST_METHOD.equals(request.getMethod()))){
            try {
                validate(new ServletWebRequest(request),SecurityConstants.DEFAULT_SMS_LOG_URL);
                filterChain.doFilter(request, response);
            } catch (ValidateCodeException e) {
                gorillaAuthenticationFailureHandler.onAuthenticationFailure(request, response, e);
                return;
            }
        }else{
            filterChain.doFilter(request, response);
        }

    }

    private void validate(ServletWebRequest request,String loginUri) throws ServletRequestBindingException, ValidateCodeException {
        if(loginUri.equals(SecurityConstants.DEFAULT_LOGIN_URL)){
            String imagecodeInRequest = ServletRequestUtils.getStringParameter(request.getRequest(), SecurityConstants.DEFAULT_PARAMETER_NAME_IMAGECODE);
            if(StringUtils.isNotBlank(imagecodeInRequest)){
                ValidCode codeInSession = (ValidCode) sessionStrategy.getAttribute(request, GorillaSecurityController.IMAGECODE_SESSION_KEY);
                if (StringUtils.isEmpty(imagecodeInRequest)) {
                    throw new ValidateCodeException("图型验证码不能为空");
                }
                if (codeInSession == null) {
                    throw new ValidateCodeException("图型验证码不存在");
                }
                if (codeInSession.isExpried()) {
                    sessionStrategy.removeAttribute(request, GorillaSecurityController.IMAGECODE_SESSION_KEY);
                    throw new ValidateCodeException("图型验证码已过期");
                }
                if (!StringUtils.upperCase(imagecodeInRequest).equals(StringUtils.upperCase(codeInSession.getCode()))) {
                    throw new ValidateCodeException("图型验证码不匹配");
                }
                sessionStrategy.removeAttribute(request, GorillaSecurityController.IMAGECODE_SESSION_KEY);
            }
        }else if(loginUri.equals(SecurityConstants.DEFAULT_SMS_LOG_URL)){
            String smscodeInRequest = ServletRequestUtils.getStringParameter(request.getRequest(), SecurityConstants.DEFAULT_PARAMETER_NAME_SMSCODE);
            SmsValidCode codeInSession = (SmsValidCode) sessionStrategy.getAttribute(request, GorillaSecurityController.SMSCODE_SESSION_KEY);
            if (StringUtils.isEmpty(smscodeInRequest)) {
                throw new ValidateCodeException("短信验证码不能为空");
            }
            if (codeInSession == null) {
                throw new ValidateCodeException("短信验证码不存在");
            }
            if (codeInSession.isExpried()) {
                sessionStrategy.removeAttribute(request, GorillaSecurityController.IMAGECODE_SESSION_KEY);
                throw new ValidateCodeException("短信验证码已过期");
            }
            if (!StringUtils.upperCase(smscodeInRequest).equals(StringUtils.upperCase(codeInSession.getCode()))) {
                throw new ValidateCodeException("短信验证码不匹配");
            }
            sessionStrategy.removeAttribute(request, GorillaSecurityController.IMAGECODE_SESSION_KEY);
        }

    }

    public GorillaAuthenticationFailureHandler getGorillaAuthenticationFailureHandler() {
        return gorillaAuthenticationFailureHandler;
    }

    public void setGorillaAuthenticationFailureHandler(GorillaAuthenticationFailureHandler gorillaAuthenticationFailureHandler) {
        this.gorillaAuthenticationFailureHandler = gorillaAuthenticationFailureHandler;
    }
}
